package com.credithc.signature.manager.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.credithc.signature.common.constant.FacadeConstant;
import com.credithc.signature.common.constant.ResponseEnum;
import com.credithc.signature.manager.constant.MsgConstant;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述：响应工具类<br/>
 * 作者：sunyang
 * 创建：2019/5/28 14:47
 * 版本：v1.0.0<br/>
 */
public class ResponseUtil {

    private static ConcurrentHashMap<Integer, String> response = new ConcurrentHashMap();

    /**
     * 根据响应码获取响应消息
     * @param code 响应码
     */
    public static String getResponseMessage(Integer code){
        if (StringUtils.isBlank(response.get(code))) {
            synchronized (ResponseUtil.class){
                if (StringUtils.isBlank(response.get(code))){
                    response.put(code, generateMessage(code));
                }
            }
        }
        return response.get(code);
    }

    protected static String generateMessage(Integer code){
        JSONObject json = new JSONObject();
        json.put(FacadeConstant.CODE, code);
        json.put(FacadeConstant.MESSAGE, StringUtils.trimToEmpty(ResponseEnum.ofMap().get(code)));
        return JSON.toJSONString(json);
    }

    public static Object getResponseMessageData(Integer code, Object data) {
        synchronized (ResponseUtil.class) {
            return generateMessageData(code, data);
        }
    }

    public static Object getResponseMessageMap(Integer code, String msg) {
        synchronized (ResponseUtil.class) {
            return generateMessageMap(code, msg);
        }
    }

    protected static Object generateMessageData(Integer code, Object data) {
        JSONObject json = new JSONObject();
        json.put(MsgConstant.CODE, code);
        json.put(MsgConstant.MESSAGE, StringUtils.trimToEmpty(ResponseEnum.ofMap().get(code)));
        json.put(MsgConstant.DATA, data);
        return json;
    }

    protected static Object generateMessageMap(Integer code, String msg) {
        JSONObject json = new JSONObject();
        json.put(MsgConstant.CODE, code);
        json.put(MsgConstant.MESSAGE, msg);
        json.put(MsgConstant.DATA, null);
        return json;
    }
}
